package com.scienceplus.dgraph_import;

import com.google.gson.Gson;
import com.google.protobuf.ByteString;
import io.dgraph.DgraphClient;
import io.dgraph.DgraphGrpc;
import io.dgraph.DgraphGrpc.DgraphStub;
import io.dgraph.DgraphProto;
import io.dgraph.DgraphProto.Mutation;
import io.dgraph.DgraphProto.Operation;
import io.dgraph.DgraphProto.Response;
import io.dgraph.Transaction;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Metadata;
import io.grpc.stub.MetadataUtils;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class TestBatchImportData {
    private static final String TEST_HOSTNAME = "localhost";
    private static final int TEST_PORT = 9180;

    //创建dgraph
    private static DgraphClient createDgraphClient(boolean withAuthHeader) {
        ManagedChannel channel =
                ManagedChannelBuilder.forAddress(TEST_HOSTNAME, TEST_PORT).usePlaintext().build();
        DgraphStub stub = DgraphGrpc.newStub(channel);

        if (withAuthHeader) {
            Metadata metadata = new Metadata();
            metadata.put(
                    Metadata.Key.of("auth-token", Metadata.ASCII_STRING_MARSHALLER), "the-auth-token-value");
            stub = MetadataUtils.attachHeaders(stub, metadata);
        }

        return new DgraphClient(stub);
    }

    public static void main(final String[] args) {
        DgraphClient dgraphClient = createDgraphClient(false);

        // Initialize
        // dgraphClient.alter(Operation.newBuilder().setDropAll(true).build());
        Gson gson = new Gson(); // For JSON encode/decode

        //读取文件
        getJsonLine(dgraphClient);

        // 查询
        //long time1 = System.currentTimeMillis();
        //String query =
        //        "query all($a: string){\n" + "all(func: eq(name, $a)) {\n" + "    name\n" + "  }\n" + "}";
        //Map<String, String> vars = Collections.singletonMap("$a", "91999");
        //Response res = dgraphClient.newTransaction().queryWithVars(query, vars);
        // 反序列化
        //People ppl = gson.fromJson(res.getJson().toStringUtf8(), People.class);

        // 输出结果
        //System.out.printf("people found: %d\n", ppl.all.size());
        //long time2 = System.currentTimeMillis();
        //System.out.println(time2-time1);
        //ppl.all.forEach(person -> System.out.println(person.name));
    }

    public static void commit(DgraphClient dgraphClient, int begin, int end, int temp) {
        Gson gson = new Gson();
        Transaction txn4 = dgraphClient.newTransaction();
        try {
            StringBuilder json = new StringBuilder();

            json.append("{\"rows\":[");
            for (int i = begin; i < end; i++) {
                //初始化数据
                Person p = new Person();
                p.name = String.valueOf(i);
                //序列化为string
                if (i != temp) {
                    json.append(gson.toJson(p)).append(",");
                } else {
                    json.append(gson.toJson(p));
                }
            }
            json.append("]}");

            // 运行mutation(数据突变--修改存储在Dgraph中的图结构 )
            Mutation mu = Mutation.newBuilder().setSetJson(ByteString.copyFromUtf8(json.toString())).build();
            txn4.mutate(mu);
            txn4.commit();

        } finally {
            txn4.discard();
        }
    }


    static class Person {
        String name;

        Person() {
        }
    }

    static class People {
        List<Person> all;

        People() {
        }
    }

    public static void getJsonLine(DgraphClient dgraphClient) {
        Gson gson = new Gson();
        Transaction txn4 = dgraphClient.newTransaction();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("D:\\java_projects\\dgraph_import\\src\\main\\resources\\100.json"));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String paper_json = "";
        int count = 0;
        try {
            if (br != null) {
                while (null != (paper_json = br.readLine())) {
                    count++;
                    Paper paper = gson.fromJson(paper_json, Paper.class);
                    PaperSerialized new_paper = new PaperSerialized(paper);
                    String new_json = gson.toJson(new_paper);
                    System.out.println(">>" + new_json);
                    // 运行mutation(数据突变--修改存储在Dgraph中的图结构 )
                    Mutation mu = Mutation.newBuilder().setSetJson(ByteString.copyFromUtf8(new_json)).build();
                    txn4.mutate(mu);
                }
                txn4.commit();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("出现问题的行数:" + count);
            e.printStackTrace();
        } finally {
            txn4.discard();
        }
        try {
            if (br != null) {
                br.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
